package com.shop.common.validator;

import com.shop.common.validator.annotation.IdCard;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class IdCardValidator implements ConstraintValidator<IdCard, String> {

    @Override
    public boolean isValid(String idCard, ConstraintValidatorContext context) {
        // 身份证号码长度为18位
        if (idCard.length() != 18) {
            return false;
        }
        // 校验前17位是否为数字
        for (int i = 0; i < 17; i++) {
            if (!Character.isDigit(idCard.charAt(i))) {
                return false;
            }
        }
        // 校验最后一位是否为数字或X
        char lastChar = idCard.charAt(17);
        if (!Character.isDigit(lastChar) && lastChar != 'X' && lastChar != 'x') {
            return false;
        }
        // 校验身份证号码的校验码是否正确
        char[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] checkCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (idCard.charAt(i) - '0') * weights[i];
        }
        int remainder = sum % 11;
        return checkCodes[remainder] == lastChar;
    }
}
